package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.CustomException;
import com.atguigu.common.exception.ResultCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author achao
 * @version 1.0
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError -> {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            map.put(field, message);
        }));
        return R.error(ResultCodeEnum.VALID_EXCEPTION.getCode(), ResultCodeEnum.VALID_EXCEPTION.getMessage()).put("data", map);
    }
    @ExceptionHandler(CustomException.class)
    public R handleException(CustomException e) {
        return R.error(e.getCode(), e.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        return R.error(ResultCodeEnum.UNKNOWN_EXCEPTION.getCode(), ResultCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }

}
